package com.llkj.contractmanagement.contractmanagement.actor;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.llkj.contractmanagement.main.BaseActivity;
import com.llkj.contractmanagement.R;
import com.llkj.contractmanagement.contractmanagement.adapter.ActorSearchResultAdapter;
import com.llkj.contractmanagement.customview.TitleBar;
import com.llkj.contractmanagement.http.HttpMethod;
import com.llkj.contractmanagement.http.UrlConfig;
import com.llkj.contractmanagement.main.MyApplication;
import com.llkj.contractmanagement.model.ActorBean;
import com.llkj.contractmanagement.model.UserInfoBean;
import com.llkj.contractmanagement.utils.GsonUtil;
import com.llkj.contractmanagement.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * author: dong.yj
 * created on: 2016/8/17 9:59
 * description:搜索结果界面
 */
public class ActorSearchResultActivity extends BaseActivity implements AdapterView.OnItemClickListener, TextWatcher, View.OnClickListener, View.OnKeyListener, BGARefreshLayout.BGARefreshLayoutDelegate {

    @Bind(R.id.bga_refresh)
    BGARefreshLayout bgaRefreshLayout;
    @Bind(R.id.et_search_result)
    EditText etSearchResult;
    @Bind(R.id.title_search_result)
    TitleBar titleBar;
    @Bind(R.id.lv_search_result)
    ListView lvSearchResult;
    @Bind(R.id.iv_delete)
    ImageView iv_delete;
    ActorSearchResultAdapter adapter;
    private List<ActorBean.YrlistBean> resultsList;

    private int page = 1;//页数
    private String name;//关键字
    private UserInfoBean userInfoBean;
    private boolean isEnd;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_searchresult;
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        init();
    }

    private void init() {
        initData();
        setListener();
    }

    private void initData() {
        bgaRefreshLayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApplication.getInstance(), true));
        bgaRefreshLayout.setPullDownRefreshEnable(false);
        userInfoBean = UserInfoBean.getInstance();
        resultsList = new ArrayList<>();
        adapter = new ActorSearchResultAdapter(this, resultsList);
        lvSearchResult.setAdapter(adapter);
    }

    private void setListener() {
        bgaRefreshLayout.setDelegate(this);
        iv_delete.setOnClickListener(this);
        titleBar.setTopBarClickListener(this);
        lvSearchResult.setOnItemClickListener(this);
        etSearchResult.addTextChangedListener(this);
        etSearchResult.setOnKeyListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //相应页面跳转
        Intent intent = new Intent(this, ActorDetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("YrList", resultsList.get(position));
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(s)) {
            iv_delete.setVisibility(View.VISIBLE);
        } else {
            iv_delete.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    public void afterTextChanged(Editable s) {
        name = s.toString();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_delete:
                etSearchResult.setText("");
                break;
        }
    }

    public void requestSousuoYrName() {
        if (TextUtils.isEmpty(name)) {
            ToastUtil.makeShortText(this, "请输入搜索条件");
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("page", page + "");
        map.put("name", name);
        map.put("user_id", userInfoBean.getId());
        map.put("token", userInfoBean.getToken());
        HttpMethod.sousuoYrname(this, this, map, UrlConfig.HTTP_SOUSUOYRNAME);
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            // 先隐藏键盘
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(ActorSearchResultActivity.this.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
            //进行搜索操作
            requestSousuoYrName();
        }
        return false;
    }

    @Override
    public void onSuccessHttp(String responseInfo, int resultCode) {
        super.onSuccessHttp(responseInfo, resultCode);
        switch (resultCode) {
            case UrlConfig.HTTP_SOUSUOYRNAME:
                ActorBean actorBean = GsonUtil.GsonToBean(responseInfo, ActorBean.class);
                if (actorBean != null) {
                    List<ActorBean.YrlistBean> addList = actorBean.getYrlist();
                    if (addList.size() > 0 && addList != null) {
                        if (page == 1) {
                            resultsList.clear();
                        }
                        resultsList.addAll(addList);
                        adapter.notifyDataSetChanged();
                        bgaRefreshLayout.endLoadingMore();
                    } else {
                        adapter.notifyDataSetChanged();
                        if (page == 1) {
                            ToastUtil.makeShortText(this, "无相关搜索！");
                        } else {
                            ToastUtil.makeShortText(this, "没有更多数据了！");
                            bgaRefreshLayout.endLoadingMore();
                        }
                    }
                }
                break;
        }
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {

    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        page++;
        if (isEnd) {
            return false;
        }
        loadMore();
        return true;
    }

    private void loadMore() {
        requestSousuoYrName();
    }
}

